﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading;
#if NETCORE
using Microsoft.AspNetCore.Http;
#endif
namespace NFinal.Middleware.Proxy
{
#if NETCORE
    public class CoreProxyMiddleware : ProxyMiddleware<HttpContext>
    {
        public CoreProxyMiddleware(RequestDelegate next, ProxyConfig config)
            : base((context) => { return next(context); },config)
        {

        }
        public override void AddRequestHeadersToHttpRequestMessage(HttpContext context, HttpRequestMessage message)
        {
            var headers = context.Request.Headers;
            foreach (var header in headers)
            {
                AddRequestHeaderToHttpRequestMessage(context, message, header.Key, header.Value);
            }
        }
        public override void AddOrUpdateResponseHeader(HttpContext context, string key, string[] value)
        {
            if (context.Response.Headers.ContainsKey(key))
            {
                context.Response.Headers[key] = value;
            }
            else
            {
                context.Response.Headers.Add(key, value);
            }
        }
        public override CancellationToken GetCancellationToken(HttpContext context)
        {
            return context?.RequestAborted ?? CancellationToken.None;
        }
        public override Stream GetRequestBody(HttpContext context)
        {
            return context.Request.Body;
        }
        public override string GetRequestMethod(HttpContext context)
        {
            return context.Request.Method;
        }
        public override string GetRequestPath(HttpContext context)
        {
            return context.Request.Path;
        }
        public override string GetRequestQueryString(HttpContext context)
        {
            return context.Request.QueryString.Value;
        }
        public override Stream GetResponseBody(HttpContext context)
        {
            return context.Response.Body;
        }
        public override void RemoveResponseHeader(HttpContext context, string key)
        {
            context.Response.Headers.Remove(key);
        }
        public override void SetResponseStatusCode(HttpContext context, int statusCode)
        {
            context.Response.StatusCode = statusCode;
        }
    }
#endif
}
